package wsz.consumer.proxy;

import com.alibaba.fastjson.JSON;
import wsz.common.RpcRequest;
import wsz.common.RpcResponse;
import wsz.consumer.client.RpcClient;

import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * @author wsz
 * @date 2021/11/30 18:29
 **/
public class RpcClientProxy {

    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass},
                (proxy, method, args) -> {
                    RpcRequest rpcRequest = new RpcRequest();
                    rpcRequest.setRequestId(UUID.randomUUID().toString());
                    rpcRequest.setClassName(method.getDeclaringClass().getName());
                    rpcRequest.setMethodName(method.getName());
                    rpcRequest.setParameterTypes(method.getParameterTypes());
                    rpcRequest.setParameters(args);


                    RpcClient rpcClient = new RpcClient("127.0.0.1", 8099);
                    try {
                        Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));

                        RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                        if (rpcResponse.getError() != null) {
                            throw new RuntimeException(rpcResponse.getError());
                        }
                        Object result = rpcResponse.getResult();
                        return JSON.parseObject(result.toString(), method.getReturnType());
                    } catch (Exception ex) {
                        throw ex;
                    } finally {
                        rpcClient.close();
                    }
                });
    }
}
